package io.github.wppli.trigger.http;

import io.github.wppli.types.common.OssUtil;
import io.github.wppli.types.model.Response;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 文件控制器
 * @author li--jiaqiang 2025−03−10
 */
@Slf4j
@RestController
@RequestMapping("/file")
@AllArgsConstructor
@CrossOrigin(value = {"${app.config.cross-origin:http://116.198.239.101:3000/}", "http://localhost:3000/"})
public class FileController {

    private final OssUtil ossUtil;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Response<String> uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        try {
            if (multipartFile.isEmpty()) {
                return Response.error();
            }
            // 获取原始文件名
            String originalFilename = multipartFile.getOriginalFilename();
            if (!StringUtils.hasLength(originalFilename)) {
                return Response.error("invalid file.");
            }
            // 获取文件后缀
            String suffix = originalFilename.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            // 生成唯一文件名
            String fileName = UUID.randomUUID() + suffix;
            // 调用方法
            String url = ossUtil.ossUploadFile(fileName, multipartFile.getInputStream());

            return Response.ok(url);

        } catch (Exception e) {
            return Response.systemError();
        }

    }

}